package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.FileUploadVo;
import com.ybkj.daijia.common.MediaUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.sales.ActivityManage;
import com.ybkj.daijia.server.sales.ActivityManage.ServiceType;
import com.ybkj.daijia.server.service.ActivityManageService;
import com.ybkj.daijia.server.service.CompanyService;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "activitymanage")
public class ActivityManageController {

    @Autowired
    private ActivityManageService activityManageService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private CompanyService companyService;


    @RequestMapping(value = "activitymanage", method = RequestMethod.GET)
    public ModelAndView activityManage() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("activitymanage")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("activitymanage/activitymanage");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "activitymanageData", method = RequestMethod.GET)
    public @ResponseBody
    Page<ActivityManage> activitymanageData() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("activitymanage")) {

            Page<ActivityManage> result = activityManageService.findAll();

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "addActivityManage", method = RequestMethod.GET)
    public ModelAndView addActivityManage(HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("activitymanage")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("companys", companyService.findAll());
            mv.addObject("activityManage", activityManageService.findAll());
            mv.setViewName("activitymanage/addactivitymanage");

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            req.getSession().setAttribute("upload_img_logo_token", time_token);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 创建活动信息
     * @param companyIds
     * @param companyNames
     * @param centreActivityImage
     * @param businessActivityImage
     * @param chainedAddress
     * @param serviceType
     * @param sort
     * @param showLocation
     * @param start
     * @param end
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<ActivityManage> create(
        @RequestParam(required = false, value = "companyIds") String companyIds,
        @RequestParam(required = false, value = "companyNames") String companyNames,
        @RequestParam(required = false, value = "centreActivityImage") String centreActivityImage,
        @RequestParam(required = false, value = "businessActivityImage") String businessActivityImage,
        @RequestParam(required = false, value = "chainedAddress") String chainedAddress,
        @RequestParam(required = true, value = "serviceType") ServiceType serviceType,
        @RequestParam(required = true, value = "sort") Long sort,
        @RequestParam(required = true, value = "showLocation") String showLocation,
        @RequestParam(required = true, value = "start") String start,
        @RequestParam(required = false, value = "end") String end) throws ParseException {

        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("activitymanage")) {
            ActivityManage activityManage = new ActivityManage();
            if (showLocation.contains("activitycentre")) {
                activityManage.setCentreActivityImage(centreActivityImage);
            }
            if (showLocation.contains("business")) {
                activityManage.setBusinessActivityImage(businessActivityImage);
            }
            if (StringUtils.isNotBlank(chainedAddress)) {
                activityManage.setChainedAddress(chainedAddress);
            }
            activityManage.setServiceType(serviceType);
            activityManage.setSort(sort);
            activityManage.setShowLocation(showLocation);
            activityManage.setStart(DateUtils.parseDate(start, "yyyy-MM-dd").getTime());
            if (StringUtils.isNotBlank(end)) {
                activityManage.setEnd(DateUtils.parseDate(end, "yyyy-MM-dd").getTime());
            }

            if (principal.isCompanyType()) {
                activityManage.setCompanyIds(companyIds);
                activityManage.setCompanyName(companyNames);
            } else {
                activityManage.setCompanyIds(principal.getCompanyId().toString());
                activityManage.setCompanyName(principal.getCompanyAbbreviation());
            }

            result = activityManageService.create(activityManage);
            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }
    }

    /**
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<ActivityManage> delete(Long id) {

        Subject subject = SecurityUtils.getSubject();

        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        if (subject.isPermitted("activitymanage")) {

            if (null != id) {
                result = activityManageService.delete(id);

                result.setSuccess(true);
                result.setMessage("操作成功");

            } else {
                result.setMessage("没有可以操作的数据");
            }

        } else {
            result.setMessage("您没有该权限");
        }

        return result;

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(HttpServletRequest req, @PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("activitymanage")) {
            ModelAndView mv = new ModelAndView();

            ActivityManage activityManage = activityManageService.findOne(id);
            mv.addObject("companys", companyService.findAll());
            mv.addObject("activityManage", activityManage);
            mv.setViewName("activitymanage/editactivitymanage");

            //等保 不能重复上传
            Long time_token = System.currentTimeMillis();
            req.getSession().setAttribute("upload_img_logo_token", time_token);

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 修改活动信息
     *
     * @param id
     * @param chainedAddress
     * @param serviceType
     * @param sort
     * @param showLocation
     * @param end
     * @param centreActivityImage
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public @ResponseBody
    Result<ActivityManage> update(
        @RequestParam(required = false, value = "companyIds") String companyIds,
        @RequestParam(required = false, value = "companyNames") String companyNames,
        @RequestParam(required = true, value = "id") Long id,
        @RequestParam(required = false, value = "chainedAddress") String chainedAddress,
        @RequestParam(required = true, value = "serviceType") ServiceType serviceType,
        @RequestParam(required = true, value = "sort") Long sort,
        @RequestParam(required = true, value = "showLocation") String showLocation,
        @RequestParam(required = false, value = "end") String end,
        @RequestParam(required = false, value = "centreActivityImage") String centreActivityImage,
        @RequestParam(required = false, value = "businessActivityImage") String businessActivityImage)
        throws ParseException {

        Result<ActivityManage> result = new Result<ActivityManage>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("activitymanage")) {

            ActivityManage activityManage = new ActivityManage();
            activityManage.setId(id);
            if (showLocation.contains("activitycentre")) {
                activityManage.setCentreActivityImage(centreActivityImage);
            }
            if (showLocation.contains("business")) {
                activityManage.setBusinessActivityImage(businessActivityImage);
            }
            if (StringUtils.isNotBlank(chainedAddress)) {
                activityManage.setChainedAddress(chainedAddress);
            }
            activityManage.setServiceType(serviceType);
            activityManage.setSort(sort);
            activityManage.setShowLocation(showLocation);
            if (StringUtils.isNotBlank(end)) {
                activityManage.setEnd(DateUtils.parseDate(end, "yyyy-MM-dd").getTime());
            }
            if (principal.isCompanyType()) {
                activityManage.setCompanyIds(companyIds);
                activityManage.setCompanyName(companyNames);
            } else {
                activityManage.setCompanyIds(principal.getCompanyId().toString());
                activityManage.setCompanyName(principal.getCompanyAbbreviation());
            }

            result = activityManageService.update(activityManage);
            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }


    @RequestMapping(method = RequestMethod.POST, value = "uploadactivityimg")
    public @ResponseBody
    FileUploadVo uploadErrandImg(@RequestParam("imgFile") MultipartFile imgFile,
        HttpServletRequest req) throws IOException {
        FileUploadVo vo = new FileUploadVo();

        String moduleName = imgFile.getOriginalFilename();

        if (MediaUtil.isPicture(imgFile, "")) {
            String bathPath = getBasePath(req);
            SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
            Date now = new Date();
            String monthstr = monthFormat.format(now);
            String type = moduleName
                .substring(moduleName.lastIndexOf(".") + 1, moduleName.length());
            String filestr = "upload/activitymanage/" + monthstr + "/" + now.getTime() + moduleName
                .substring(moduleName.lastIndexOf("."), moduleName.length());
            String minImg = filestr.substring(0, filestr.lastIndexOf(".")) + "min." + type;
            File f = new File(bathPath, filestr);

            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }

            try {
                File tempDest = new File(System.getProperty("java.io.tmpdir"),
                    "upload_" + String.valueOf(System.nanoTime()) + ".tmp");
                imgFile.transferTo(tempDest); //上传到临时文件中
                FileUtils.copyFile(tempDest, f);
                tempDest.delete();
                try {
                    Thumbnails.of(f).size(100, 100).toFile(new File(bathPath, minImg));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                vo.setUrl(filestr);
                vo.setMinurl(minImg);
                vo.setSuccess(true);
                return vo;

            } catch (Exception e) {
                vo.setMsg(e.getMessage());
                vo.setSuccess(false);
                return vo;
            }
        } else {
            vo.setMsg("只能上传图片");
            vo.setSuccess(false);
            return vo;
        }

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }


}

